package ace.cmp.rest.spring.data.jdbc.querydsl.test.core.manager.impl;

import ace.cmp.rest.spring.data.jdbc.querydsl.test.core.dao.repository.BaseRepository;
import ace.cmp.rest.spring.data.jdbc.querydsl.test.core.manager.BaseManager;
import ace.cmp.spring.util.core.SpringUtils;
import lombok.AccessLevel;
import lombok.Getter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.ResolvableType;

/**
 * @author caspar
 * @date 2023/9/21 14:13
 */
public abstract class BaseManagerImpl<TEntity, TId> implements BaseManager<TEntity, TId> {
  @Autowired private SpringUtils springUtils;

  @Autowired
  @Getter(AccessLevel.PUBLIC)
  private BaseRepository<TEntity, TId> repository;

  public BaseRepository<TEntity, TId> getRepositoryFromSpringUtils(
      Class<TEntity> entityClass, Class<TId> idClass) {
    ParameterizedTypeReference<BaseRepository<TEntity, TId>> typeReference =
        new ParameterizedTypeReference<>() {};
    ObjectProvider<BaseRepository<TEntity, TId>> objectProvider =
        springUtils
            .getDefaultListableBeanFactory()
            .getBeanProvider(ResolvableType.forType(typeReference));
    return objectProvider.getIfAvailable();
  }
}
